Adventures In Raspberry Pi by Carrie Anne Philbin

Adventures In Raspberry Pi by Carrie Anne Philbin

Author:Carrie Anne Philbin [Philbin, Carrie Anne]
Language: eng
Format: azw, pdf
Publisher: Wiley
Published: 2013-12-03T00:00:00+00:00


Using a while Loop

So far, the player has not been required to input specific answers in order for the game to move on. If the player does not input anything at all, the game simply stalls; and if the player types an unrecognized answer, the game says, “You think for a while”. You want the player to input one of the responses that you have defined, left or right, to move on to the next location. You can ensure she inputs one of the desired responses by adding a while loop to your code. This will loop the user input question until the player types in a response that you were looking for—left or right—to move on. For example:

# Loop until we get a recognised response

while True:

direction1 = input(“Do you want to go left or right? “)

direction1 = direction1.lower()

if direction1 == “left”:

print(“You walk to the cave and notice there is an

opening.”)

break # leave the loop

elif direction1 == “right”:

print(“You walk to the beach but remember you do not

have any swimwear.”)

break # leave the loop

else:

print(“You think for a while”)

In this code, shown also in Figure 5-11, you can see in bold text the Python words while True: added before the user input question, and break added within the conditionals for left and right. The while True: condition will loop the question over and over until the player enters either left or right so that the game does not end if the player types anything else.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.